import logging

from fastapi import APIRouter, Body, Query
from tortoise.expressions import Q
from tortoise.functions import Sum
from app.controllers.appointment.space import appointment_space_controller
from app.controllers.system.dept import dept_controller
from app.controllers.system.user import user_controller
from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.models import PerformancePercentage
from app.schemas.base import Fail, Success, SuccessExtra
from app.schemas.users import *
from datetime import datetime, timedelta
import calendar

logger = logging.getLogger(__name__)

users_router = APIRouter()


@users_router.get("/list", summary="查看用户列表", dependencies=[DependCustomerAuth])
async def list_user(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    alias: str = Query("", description="用户名称，用于搜索"),
    username: str = Query("", description="用户账号，用于搜索"),
    email: str = Query("", description="邮箱地址"),
    dept_id: int = Query(0, description="部门ID"),
    yeji: int = Query(0, description="是否计算业绩"),
    start_time: str = Query(None, description=f"业绩开始时间"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    # if user.space_id:
    #     q &= Q(space_id=user.space_id)
    if username:
        q &= Q(username__contains=username)
    if alias:
        q &= Q(alias__contains=alias)
    if email:
        q &= Q(email__contains=email)
    if dept_id>0:
        q &= Q(dept_id=dept_id)
    total, user_objs = await user_controller.list(page=page, page_size=page_size, search=q)
    data = [await obj.to_dict(m2m=True, exclude_fields=["password"]) for obj in user_objs]
    space_objs = await appointment_space_controller.level_list()
    for item in data:
        dept_id = item.pop("dept_id", None)
        item["dept"] = await (await dept_controller.get(id=dept_id)).to_dict() if dept_id else {}
        if item["space_id"]:
            item["space_name"] = await appointment_space_controller.get_space_names(item["space_id"])
        else:
            item["space_name"] = "未设置门店"
        if yeji == 1:
            tc = await get_yeji(item["id"],start_time)
            item["tc"] = tc
            item["hj"] = float(item["salary"])+tc


    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

async def get_yeji(user_id:int,start_time:str):
    if start_time:
        dt = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
        # 获取当月最后一天的日期
        _, last_day = calendar.monthrange(dt.year, dt.month)
        end_time = datetime(dt.year, dt.month, last_day, 23, 59, 59)
    else:
        # 当前时间
        now = datetime.now()
        start_time = datetime(now.year, now.month, 1, 0, 0, 0)
        _, last_day = calendar.monthrange(now.year, now.month)
        end_time = datetime(now.year, now.month, last_day, 23, 59, 59)

    result = await PerformancePercentage.filter(
        user_id=user_id,
        created_at__range=(start_time, end_time)
    ).annotate(total=Sum('price')).first()

    if result and result.total is not None:  # 检查是否存在且非 None
        total = float(result.total)
    else:
        total = 0.0  # 默认值

    return total



@users_router.get("/get", summary="查看用户")
async def get_user(
    user_id: int = Query(..., description="用户ID"),
):
    user_obj = await user_controller.get(id=user_id)
    user_dict = await user_obj.to_dict(exclude_fields=["password"])
    return Success(data=user_dict)


@users_router.post("/create", summary="创建用户")
async def create_user(
    user_in: UserCreate,
):
    user = await user_controller.get_by_email(user_in.email)
    if user:
        return Fail(code=400, msg="The users with this email already exists in the system.")
    new_user = await user_controller.create_user(obj_in=user_in)
    await user_controller.update_roles(new_user, user_in.role_ids)
    return Success(msg="Created Successfully")


@users_router.post("/update", summary="更新用户")
async def update_user(user_in: UserUpdate):
    #查询是否超级用户,无法禁用和删除
    # if user_in.is_superuser:
    #     return Fail(code=400, msg="超级用户不允许编辑")
    user = await user_controller.update(id=user_in.id, obj_in=user_in)
    await user_controller.update_roles(user, user_in.role_ids)
    return Success(msg="Updated Successfully")


@users_router.delete("/delete", summary="删除用户")
async def delete_user(
    user_id: int = Query(..., description="用户ID"),
):
    user = await user_controller.get_detail(user_id)
    if user.is_superuser:
        return Fail(code=400, msg="超级用户不允许删除")
    await user_controller.remove(id=user_id)
    return Success(msg="Deleted Successfully")


@users_router.post("/reset_password", summary="重置密码")
async def reset_password(user_id: int = Body(..., description="用户ID")):
    await user_controller.reset_password(user_id)
    return Success(msg="密码已重置为123456")
